package com.medicine.product.controller;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.medicine.product.utils.HttpUtils;
import com.medicine.product.utils.ItextPdfUtils;
import com.medicine.product.utils.PicToPdfUtil;
import gui.ava.html.image.generator.HtmlImageGenerator;
import gui.ava.html.parser.HtmlParser;
import gui.ava.html.parser.HtmlParserImpl;
import gui.ava.html.renderer.ImageRenderer;
import gui.ava.html.renderer.ImageRendererImpl;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.HashMap;
import java.util.Map;


/**
 * @author lynn
 * @version 1.0
 * @date 2021/10/28
 */
public class Test {
    public static void main(String[] args) throws Exception {

        ClassPathResource classPathResource = new ClassPathResource("template/处方2.pdf");

        PdfReader reader;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            reader = new PdfReader(classPathResource.getInputStream());
            bos = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            File file = new File("D:/测试用.pdf");
            file.createNewFile();



            Map<String, String> map = new HashMap<>();
            map.put("shospitalname", "广州中研皮肤病专科门诊部");
            map.put("type", "自费");
            map.put("Departments", "皮肤科");
            map.put("name", "刘星");
            map.put("age", "25");
            map.put("birthday", "1996-02-28");
            map.put("diagnose", "花粉过敏");
            map.put("date", "2021-11-03");
            map.put("address", "湖南省怀化市麻阳县");
            map.put("phone", "15700758028");
            String drug="板蓝根   30g/袋   10袋            ";
            drug+="杜仲   10g/袋    10袋           ";
            drug+="艾草   40g/袋    10袋              ";
            drug+="神仙水   40g/袋    10袋           ";
            map.put("drug", drug);
            map.put("num", "共1包");
            map.put("usage", "冲热水喝");
            map.put("physician", "杨文");
            map.put("audit", "高武强");
            map.put("review", "杨文");
            map.put("dispensing", "杨文");
//            map.put("tu", "杨文");

            /**
             * 如果实参传入了，图片和坐标值，则添加图片
             */
            // 图片路径
            String imagePath = "d:\\11.jpg";
            InputStream imgInputStream = new FileInputStream(new File(imagePath));

            byte[] bytes = toByteArray(imgInputStream);
            if(bytes != null){
                Image image = Image.getInstance(bytes);
                image.setAbsolutePosition(390,180);
                PdfContentByte underContent = stamper.getOverContent(1);//  getOverContent 图片会覆盖在文字上层
                image.scaleAbsolute(120,120);// 指定图片的宽高
                underContent.addImage(image);
            }

            fillPdfCellForm(map, form);
            // true代表生成的PDF文件不可编辑
            stamper.setFormFlattening(true);
            stamper.close();

            FileOutputStream fileSteam =new FileOutputStream(file);
            fileSteam.write(bos.toByteArray());
            fileSteam.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

//        String fileName = "tableAndTitle.pdf";
        /*Document document =new Document(); // 默认页面大小是A4
        Document document =new Document(PageSize.A4); // 指定页面大小为A4*/
//        Document document =new Document(PageSize.A4,50,50,30,20); // 指定页面大小为A4，且自定义页边距(marginLeft、marginRight、marginTop、marginBottom)
//
//        PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream(fileName));
//        document.open();

        /*String fileName = "tableAndTitle.pdf";
        Test.test(fileName);*/
    }

    private static void fillPdfCellForm(Map<String, String> map, AcroFields form) throws IOException, DocumentException {
        for (Map.Entry entry : map.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            if(key.equalsIgnoreCase("shospitalname")) {
                form.setFieldProperty(key, "textsize", 22f, null);
            }
            form.setField(key, value);
        }
    }


    public static byte[] toByteArray(InputStream input){
        if(input == null){
            return null;
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (true) {
            try {
                if (!(-1 != (n = input.read(buffer)))) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }


    private static void test(String fileName) {
        Document document = new Document(PageSize.A4,50,50,30,20);
        try {
            PdfWriter.getInstance(document, new FileOutputStream(fileName));
            document.open();

            PdfPTable table = new PdfPTable(1);
            table.setKeepTogether(true);
            table.setSplitLate(false);

            PdfPTable table1 = new PdfPTable(1);
            PdfPCell cell0 = new PdfPCell();
            Paragraph p = new Paragraph("table title sample");
            p.setAlignment(1);
            p.setSpacingBefore(15f);
            cell0.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
            cell0.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//然并卵
            cell0.setPaddingTop(-2f);//把字垂直居中
            cell0.setPaddingBottom(8f);//把字垂直居中
            cell0.addElement(p);
            cell0.setBorder(0);
            table1.addCell(cell0);

            PdfPTable pTable = new PdfPTable(table1);
            document.add(pTable);

            PdfPTable table2 = new PdfPTable(2);
            float border = 1.5f;
            for (int a = 0; a < 20; a++) {
                PdfPCell cell = new PdfPCell();
                Paragraph pp;
                if (a == 0 || a == 1) {
                    pp = str2ParaByTwoFont("tableTitle" + (a + 1), 9f, BaseColor.BLACK, Font.BOLD); //小五 加粗
                    cell.setBorderWidthBottom(border);
                    cell.setBorderWidthTop(border);
                } else {
                    if (a == 18 || a == 19) {
                        cell.setBorderWidthTop(0);
                        cell.setBorderWidthBottom(border);
                    } else {
                        cell.setBorderWidthBottom(0);
                        cell.setBorderWidthTop(0);
                    }
                    pp = str2ParaByTwoFont("tableContent" + (a - 1), 9f, BaseColor.BLACK); //小五
                }
                //设置间隔的背景色
                if ((a + 1) % 2 == 0) {
                    if (((a + 1) / 2) % 2 == 1) {
                        cell.setBackgroundColor(new BaseColor(128, 128, 255));
                    } else {
                        cell.setBackgroundColor(new BaseColor(128, 255, 255));
                    }
                } else {
                    if (((a + 1) / 2) % 2 == 1) {
                        cell.setBackgroundColor(new BaseColor(128, 255, 255));
                    } else {
                        cell.setBackgroundColor(new BaseColor(128, 128, 255));
                    }
                }
                pp.setAlignment(1);
                cell.setBorderWidthLeft(0);
                cell.setBorderWidthRight(0);
                cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//然并卵
                cell.setPaddingTop(-2f);//把字垂直居中
                cell.setPaddingBottom(8f);//把字垂直居中
                cell.addElement(pp);
                table2.addCell(cell);
            }

            PdfPCell c1 = new PdfPCell();
            c1.setBorder(0);
            c1.addElement(table1);

            PdfPCell c2 = new PdfPCell();
            c2.setBorder(0);
            c2.addElement(table2);

            table.addCell(c1);
            table.addCell(c2);

            document.add(table);
            document.close();
        } catch (FileNotFoundException | DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 两种字体显示文字
     *
     * @param cont
     * @param size
     * @param color
     * @return
     */
    private static Paragraph str2ParaByTwoFont(String cont, float size, BaseColor color) {
        Paragraph res = new Paragraph();
        FontSelector selector = new FontSelector();
        //非汉字字体颜色
        Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, size);
        f1.setColor(color);
        //汉字字体颜色
        Font f2 = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED, size);
        f2.setColor(color);

        selector.addFont(f1);
        selector.addFont(f2);
        Phrase ph = selector.process(cont);
        res.add(ph);
        return res;
    }

    /**
     * 两种字体显示文字
     *
     * @param cont
     * @param size
     * @param color
     * @param bold
     * @return
     */
    private static Paragraph str2ParaByTwoFont(String cont, float size, BaseColor color, int bold) {

        Paragraph res = new Paragraph();
        FontSelector selector = new FontSelector();
        //非汉字字体颜色
        Font f1 = FontFactory.getFont(FontFactory.TIMES_ROMAN, size);
        f1.setColor(color);
        f1.setStyle(bold);
        //汉字字体颜色
        Font f2 = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED, size);
        f2.setColor(color);
        f2.setStyle(bold);

        selector.addFont(f1);
        selector.addFont(f2);
        Phrase ph = selector.process(cont);
        res.add(ph);
        return res;
    }


    //图片变pdf
        /*String source = "D:/image/车辆颜色.png";
        String target = "D:/image/1.pdf";
        PicToPdfUtil.convert(source, target);*/


        /*HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
        //加载html模版
        imageGenerator.loadHtml("http://scrm.uat.vdaifu.com/recipe.html");
        //把html写入到图片
        imageGenerator.saveAsImage("D:\\hello-world.png");*/

         /*String HtmlTemplateStr = "\t<div style=\"height: 500px;width: 500px;background: #aee0ff;\">\n" +
                "\t\t这个是一个div\n" +
                "\t\t<h1>标题</h1>\n" +
                "\t\t<ol>\n" +
                "\t\t\t<li>a</li>\n" +
                "\t\t</ol>\n" +
                "\t\t<img style=\"margin-left: 1500px;\" width=\"300px\" height=\"200px\" src=\"https://inews.gtimg.com/newsapp_bt/0/11911825373/1000\">\n" +
                "\t</div>";


        HtmlParser htmlParser = new HtmlParserImpl();
        htmlParser.loadHtml(HtmlTemplateStr);
        // html 是我的html代码
        ImageRenderer imageRenderer = new ImageRendererImpl(htmlParser);
        imageRenderer.saveImage("D:\\lcxq1.png");*/


        /*HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.setTimeout(30000);
        httpUtils.setWaitForBackgroundJavaScript(30000);
        try {
            String htmlPageStr = httpUtils.getHtmlPageResponse("http://scrm.uat.vdaifu.com/recipe.html");
            //TODO
            System.out.println(htmlPageStr);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
}
